from django.db import models,transaction
from django.db.models.signals import pre_save 
from django.dispatch import receiver 
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Topic(models.Model):
    """用户学习的主题"""
    text=models.CharField(max_length=200)
    date_added=models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User,on_delete=models.SET_NULL,null=True)
    public = models.BooleanField(default=False)
    def __str__(self):
        """返回模型字符串表示"""
        return f"{self.text}"

@classmethod
def Create_reusing_id(cls,**kwargs):
    used_ids = set(cls.objects.values_list('id',flat=True))
    if not used_ids:
        return 1
    else:
        max_used_id=max(used_ids)
        all_possible_id=set(range(1,max_used_id+1))
        free_ids=all_possible_id-used_ids
    if free_ids:
        return min(free_ids)
    else:
        return max_used_id+1
def save(self,*args,**kwargs):
    if not self.id:
        self.id= self.Create_reusing_id()
    super().save(*args,**kwargs)

class Entry(models.Model):
    """与主题相关的知识"""
    topic=models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True)
    text=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(null=True,blank=True)
    class Meta:
        verbose_name_plural = 'entries'#命名选项名
    def __str__(self):
        """返回模型字符串表示"""
        topic_text = self.topic.text if self.topic else "[未分类]"#检查主题是否为空
        if len(self.text) > 50:
           return f"{topic_text}| {self.text[:50]}…"
        else:
            return f"{topic_text}| {self.text}"
    def save(self, *args, **kwargs):
        if self.pk:  
            original = Entry.objects.get(pk=self.pk)
            if self.text != original.text:
                self.last_modified = timezone.now() # 内容变化时更新时间  
        super().save(*args, **kwargs)
class Friendship(models.Model):
    Status_choices = (('pending','待处理'),('accepted','已接受'),('rejected','已拒绝'))
    from_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='sent_requests')
    to_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='received_requests')
    status = models.CharField(max_length=20,choices=Status_choices,default='pending')
    created_at = models.DateTimeField(auto_now_add=True)